# -*- coding: utf-8 -*-

import json

with open('./temps/temp.x.json', mode='r', encoding='utf-8') as fp:
    ast = json.loads(fp.read())

class Node:
    nodeid = 0
    def __init__(self, ast) -> None:
        Node.nodeid += 1
        self.id = 'n'+str(Node.nodeid)
        self.label = self.extract_label(ast)

    def extract_label(self, ast):
        if label := ast.get('name'):
            return label
        elif label := ast.get('value'):
            return label
        elif label := ast.get('type'):
            return label

program = Node(ast)



def ddot():
    dot = 'digraph ast {'

    def addDotNode(node):
        nonlocal dot
        dot += '\n' + str(node.id) + '[label="'+str(node.label)+'"];'

    def addDotEdge(fnode, tnode, label):
        nonlocal dot
        dot += '\n' + str(fnode.id) + ' -> ' + str(tnode.id) + '[label="'+str(label)+'"];'

    def dumpDot():
        nonlocal dot
        dot += '\n}'
        return dot
    
    return addDotNode, addDotEdge, dumpDot

add_dot_node, add_dot_edge, dump_dot = ddot()

def traverse(node, ast):
    if not isinstance(ast, dict):
        return

    for edge, child_ast in ast.items():
        if edge in ('loc', 'range', 'name', 'value'):
            continue

        if isinstance(child_ast, list):
            for i in range(len(child_ast)):
                cchild_ast = child_ast[i]

                if isinstance(cchild_ast, dict):
                    cchild = Node(cchild_ast)
                    add_dot_node(cchild)
                    add_dot_edge(node, cchild, edge+':'+str(i))
                    traverse(cchild, cchild_ast)

        else:
            if isinstance(child_ast, dict):
                child = Node(child_ast)
                add_dot_node(child)
                add_dot_edge(node, child, edge)
                traverse(child, child_ast)

add_dot_node(program)
traverse(program, ast)

with open('./temps/temp.y.dot', mode='w', encoding='utf-8') as fp:
    fp.write(dump_dot())
